<template>
  <div class="app-container">
    <!-- 用户列表 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="用户名/手机号"
            clearable
            class="w-200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="!w-[100px]"
          >
            <el-option
              v-for="item in optionList.statusOptions()"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            class="!w-240px"
            v-model="dateTimeRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['sys:user:add']"
              type="success"
              @click="openDialog('user-form')"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              v-hasPerm="['sys:user:delete']"
              type="danger"
              :disabled="removeIds.length === 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="pageData.arr"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          key="username"
          label="用户名"
          align="center"
          prop="username"
        />
        <el-table-column
          label="性别"
          width="100"
          align="center"
          prop="genderLabel"
        >
          <template #default="scope">
            {{ getOptionText(options, scope.row.gender) }}
          </template>
        </el-table-column>
        <el-table-column
          label="手机号码"
          align="center"
          prop="mobile"
          width="120"
        />
        <el-table-column label="邮箱" align="center" prop="email" width="120" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">{{
              optionList.getOptionText(
                optionList.statusOptions(),
                scope.row.status
              )
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
        />
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:user:edit']"
              type="primary"
              link
              size="small"
              @click="openDialog('user-form', scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['sys:user:delete']"
              type="primary"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <userAddAndUpdate
      v-if="dialog.visible"
      v-model:visible="dialog.visible"
      :title="dialog.title"
      :id="dialog.id"
      @handle-query="handleQuery"
    />
  </div>
</template>

<!-- 用户管理 -->
<script setup lang="ts">
defineOptions({
  name: 'User',
  inheritAttrs: false
})

import { getDictOptions } from '@/api/dict'
import {
  getUserPage,
  // getUserForm,
  deleteUsers
  // addUser,
  // updateUser,
  // updateUserPassword,
  // downloadTemplateApi,
  // exportUser
  // importUser
} from '@/api/user'

import { UserForm, UserQuery, UserPageVO } from '@/api/user/types'

const queryFormRef = ref(ElForm) // 查询表单
const queryParams = reactive<UserQuery>({
  pageNum: 1,
  pageSize: 10
})
const optionList: any = inject('optionList')
const dateTimeRange = ref('')
const loading = ref(false) //  加载状态
const removeIds = ref([]) // 删除用户ID集合 用于批量删除
const pageData = reactive({
  arr: []
}) // 用户分页数据
const total = ref(0) // 数据总数
// 弹窗对象
const dialog = reactive({
  visible: false,
  title: '',
  id: 0
})
const options: Ref<OptionType[]> = ref([]) // 字典下拉数据源

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0]
    queryParams.endTime = newVal[1]
  }
})

/** 查询 */
function handleQuery() {
  loading.value = true
  getUserPage(queryParams)
    .then(({ data }: any) => {
      pageData.arr = data.list
      total.value = data.total
    })
    .finally(() => {
      loading.value = false
    })
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields()
  dateTimeRange.value = ''
  queryParams.pageNum = 1
  queryParams.startTime = undefined
  queryParams.endTime = undefined
  handleQuery()
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id)
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  用户表单：user-form | 用户导入：user-import
 * @param id 用户ID
 */
async function openDialog(type: string, id?: number) {
  dialog.visible = true
  dialog.id = id || 0
  id ? (dialog.title = '修改用户') : (dialog.title = '新增用户')
  // getUserForm(id).then(({ data }) => {
  //   Object.assign(formData, { ...data })
  // })
}

/** 删除用户 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(',')
  if (!userIds) {
    ElMessage.warning('请勾选删除项')
    return
  }
  ElMessageBox.confirm('确认删除用户?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function () {
    deleteUsers(userIds).then(() => {
      ElMessage.success('删除成功')
      resetQuery()
    })
  })
}

const getOptionText = (
  dataList: any,
  value: string | number,
  defaultVal = ''
) => {
  const obj: any = dataList.find((item: any) => item.value === value)
  return obj ? obj.label : defaultVal
}

onMounted(() => {
  handleQuery()
  // 根据字典类型编码(typeCode)获取字典选项
  getDictOptions('gender').then((res) => {
    options.value = res.data
  })
})
</script>

<style lang="scss"></style>
